package cn.samler.shopapi.Handler;

import cn.samler.shopapi.Model.Sys.Response;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

@ControllerAdvice
public class RequestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handler(Exception e) {
        e.printStackTrace();
        if (e instanceof MethodArgumentNotValidException) {
            ArrayList<String> msgList = new ArrayList<>();
            for (ObjectError err : ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors()) {
                msgList.add(err.getDefaultMessage());
            }

            return Response.failure(msgList);
        }
        return Response.failure(e.toString());
    }
}
